<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\analysis\data\info;

use app\enum\AnalysisEnum;
use app\model\mongo\MongoInfoModel;
use app\model\mongo\MongoReportModel;
use app\service\analysis\info\PicInfoService;
use app\service\analysis\info\VideoInfoService;
use app\service\BaseService;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

final class SystemMaterialService extends BaseService
{
    /**
     * @var int 媒体类型
     */
    private int $mediaId;

    /**
     * @var int 任务类型
     */
    private int $taskType;

    /**
     * @var null|PicInfoService|VideoInfoService 素材服务
     */
    private $service;

    public function __construct(int $mediaId = 0, int $taskType = 0)
    {
        $this->mediaId = $mediaId;
        $this->taskType = $taskType;
        $this->setService();
    }

    /**
     * 判断是否是服务
     */
    public function isService(): bool
    {
        return $this->service->isService();
    }

    /**
     * 待刷新数据.
     * @return array|Collection|MongoReportModel[]
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getList()
    {
        return $this->service->getWaitSystemList();
    }

    /**
     * 执行任务
     */
    public function runTask(MongoInfoModel $model): bool
    {
        if (! $model->getKey()) {
            return self::setError('未知素材信息');
        }

        if ($this->service->isSystemMaterial($model)) {
            $model->setAttr('is_system', MongoInfoModel::IS_SYSTEM_MATERIAL);
        } else {
            $model->setAttr('is_system', MongoInfoModel::NOT_SYSTEM_MATERIAL);
        }

        return $model->save();
    }

    /**
     * 设置服务
     */
    private function setService()
    {
        if ($this->taskType == AnalysisEnum::TASK_TYPE_VIDEO) {
            $this->service = new VideoInfoService($this->mediaId);
        } elseif ($this->taskType == AnalysisEnum::TASK_TYPE_PICTURE) {
            $this->service = new PicInfoService($this->mediaId);
        }
    }
}
